<?php

namespace app\helpers;

use yii;

class StringHelp extends yii\helpers\StringHelper
{

    /**
     * 生成随机数字
     * @param int $length, 随机数字位数
     * @return string
     */
    public static function getRandNum($length = 4)
    {
        $ret = '';

        for ($i = 0; $i < $length; $i++) {
            $ret .= rand(0, 9);
        }

        return $ret;
    }

    /**
     * Helper::truncate_utf8_string($content,20,false); //不显示省略号
     * Helper::truncate_utf8_string($content,20); //显示省略号
     * @param $string
     * @param $length
     * @param string $etc
     * @return string
     */
    public static function truncate_utf8_string($string, $length, $etc = '...')
    {
        $result = '';
        $string = html_entity_decode(trim(strip_tags($string)), ENT_QUOTES, 'UTF-8');
        $strlen = strlen($string);
        for ($i = 0; (($i < $strlen) && ($length > 0)); $i++) {
            if ($number = strpos(str_pad(decbin(ord(substr($string, $i, 1))), 8, '0', STR_PAD_LEFT), '0')) {
                if ($length < 1.0) {
                    break;
                }
                $result .= substr($string, $i, $number);
                $length -= 1.0;
                $i += $number - 1;
            } else {
                $result .= substr($string, $i, 1);
                $length -= 0.5;
            }
        }
        $result = htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
        if ($i < $strlen) {
            $result .= $etc;
        }
        return $result;
    }

}
